from __future__ import absolute_import, division, print_function

import base64  #用64个字符表示二进制数
import os
import tarfile  #压缩文件
import tempfile  #临时文件

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import PIL  #python imaging library 图像处理库
import tensorflow.contrib.slim as slim
import tensorflow.contrib.slim.nets as nets
from six.moves import urllib  #urllib中的url指下载地址
from six.moves.urllib.request import urlretrieve

tf.reset_default_graph()
tf.logging.set_verbosity(tf.logging.ERROR)
sess = tf.InteractiveSession()

image = tf.Variable(tf.zeros((299, 299, 3)))#设置输入图像，确保训练时可以输入

def network(img,reuse):
    preprocessed=tf.multiply(tf.subtract(tf.expand_dims(image,0),0.5),2.0)
    arg_scope=nets.incepion .inception_v3_arg_scope(weight_decay=0)
    with slim.arg_scope(arg_scope):
        logits,end_points=nets.inception.inception_v3(
            preprocessed,1001,is_training=False,reuse=reuse)
        logits=logits[:,1:]
        probs=tf.nn.softmax(logits)
    return logits,probs,end_points

logits, probs, end_points = network(image, reuse=False)
data_dir='.'
checkpoint_filename=os.path.join(data_dir,'inception_v3.ckpt')
if not os.path.exists(checkpoint_filename):
    inception_tarball,_=urlretrieve(
        'http://download.tensorflow.org/models/inception_v3_2016_08_28.tar.gz')
    tarfile.open(inception_tarball,'r:gz').extractall(data_dir)

restore_vars=[
    var for var in tf.gloabal_variables() if var.name.startswith('InceptionV3/')]
saver=tf.train.Saver(restore_vars)
saver.restore(sess,os.path.join(data_dir,'inception_v3.ckpt'))

def get_feature(img,feature_layer_name):
    p,feature_values=sess.run([probs,end_points],feed_dict={image:img})
    return feature_values[feature_layer_name].squeeze()

image_urls=['https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQZT_N_NkyYcw7QXXui3-mZI-SFSmZbkGLrkME5SBJKD3sj9U_C',
    'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQX9hHM_Yze0mu5U_d5ptKJrM3bJSCPObwj1m5vQjCL5etIaa9TTQ',
    'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQrF-s_TNdfhyLk4yLxBRriRwK6aIjD-n871SjfbdMTGLYFFs95Rg',
    'http://www.dogster.com/wp-content/uploads/2015/05/husky-puppies-02.jpg',
    'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTNbX0sR7CdIYeTHjNirFCr4tjmxw6ptf0HKqvNQL3axYNzm4A5Hw',
    'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQzqwU1cF4siokKlsrgMYf1VONbAe4h2OJ_YYe1biVA1GSLPT3m',
    'http://www.anishathalye.com/media/2017/07/25/cat.jpg']
plt.figure(figsize=(12,12))
images=[]
for idx,img_url in enumerate(image_urls):
    img_path,_=urlretrieve(img_url)
    img=PIL.Image.open(img_path)
    img=img.resize((299,299))

    plt.subplot(1,8,idx+1)
    plt.axis('off')
    plt.imshow(img)
    plt.title('images[{}]'.format(idx))
    images.append(img)

layer='PreLogits'#该层为分类器前的最后一层
feature=[]
for img in images:
    img=(np.asarray(img)/255.0).astype(np.float32)
    feature=get_feature(img,layer)
    feature.append(feature)
feature_vectors=np.stack(feature)

score_feature_shape=0
try:
    print(feature_vectors.shape)
    assert feature_vectors.shape==(7,2048),'shape mismatch!'
    score_feature_shape=10
except Exception as ex:
    print(ex)

distance_euclidean=np.sum(np.power(feature_vectors,2),axis=1,keepdims=True)+np.sum(
    np.power(feature_vectors,2),axis=1,keepdims=True.T-2*np.dot(feature_vectors,feature_vectors.T))

feature_norm=feature_vectors/np.linalg.norm(
    feature_vectors,axis=1)[:,np.newaxis]
distance_cosin=np.dot(feature_norm,feature_norm.T)

plt.figure(figsize=(12,21))

for idx_img,plt_img in enumerate(images):
    order_euclidean=np.argsort(distance_euclidean[idx_img])
    order_cosin=np.argsort(distance_cosin[idx_img])[::-1]

    plt.subplot(14,8,idx_img*8*2+1)
    plt.axis('off')
    plt.imshow(plt_img)

    for idx_sim,i in enumerate(order_euclidean):
        similay_img=images[i]
        plt.subplot(14,8,idx_img*8*2+idx_sim+2)
        plt.axis('off')
        plt.title('eucl-[{}]'.format(i))

        plt.imshow(similay_img)

    for idx_sim,i in enumerate(order_cosin):
        similay_img=images[i]
        plt.subplot('off')
        plt.title('cos-[{}]'.format(i))

        plt.imshow(similay_img)
